﻿using Meiam.System.Interfaces;
using Meiam.System.Interfaces.IService;
using Meiam.System.Model.Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Meiam.System.Model.Dto;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SqlSugar;
using System.Text;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Meiam.System.Model;
using Microsoft.Extensions.Logging;
using System.IO;
using OfficeOpenXml.FormulaParsing.Excel.Functions.DateTime;
using System.Xml.Linq;
using System.Reflection.Metadata;
using OfficeOpenXml.FormulaParsing.Excel.Functions.RefAndLookup;
using Castle.Core.Resource;
using MailKit.Search;

namespace Meiam.System.Hostd.Controllers.Gokin
{
    /// <summary>
    /// TMS_下发运单车牌信息
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class TMStoWMSAddCarInfoController : ControllerBase
    {
        private readonly ILogger _logger;
        public readonly IWMSTokenCheckService _WMSTokenCheckService;
        public readonly string con;
        public readonly string con_zh;
        public readonly string con_qh;
        public readonly string con_yb;


        public TMStoWMSAddCarInfoController(ILogger<TMtoWMSAddCarInfoRequestDto> logger, IWMSTokenCheckService wmsTokenCheckService, IConfiguration _configuration, ILoggerFactory loggerFactory)
        {
            _WMSTokenCheckService = wmsTokenCheckService;
            con = _configuration.GetConnectionString("DDM_DbConnection_ZH");
            con_zh = _configuration.GetConnectionString("WMSDbConnection_ZH");
            con_qh = _configuration.GetConnectionString("WMSDbConnection");
            con_yb = _configuration.GetConnectionString("WMSDbConnection_YB");
            _logger = loggerFactory.CreateLogger<TMStoWMSAddCarInfoController>();
        }

        /// <summary>
        /// TMS_下发运单车牌信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PostTMSAddCarInfo([FromBody] TMtoWMSAddCarInfoRequestDto strparm)
        {
            string strMsg = "";
            StringBuilder strSql = new StringBuilder();
            List<string> strSqlList = new List<string>();
            Dictionary<string, string> dic = new Dictionary<string, string>(); //查询公用dic
            TMtoWMSAddCarInfoResponseDto re = new TMtoWMSAddCarInfoResponseDto();
            string fy_code = strparm.fy_code;
            string in_con = "";//目标WMS数据库
            try
            {
                if (fy_code == "")
                {
                    strMsg = "fy_code must be not null";
                }
                if (strparm.factory_code == "")
                {
                    strMsg = "factory_code must be not null";
                }
                else
                {
                    if (strparm.factory_code.Contains("zh"))
                    {
                        in_con = con_zh;
                    }
                    else
                    {
                        if (strparm.factory_code.Contains("qh"))
                        {
                            in_con = con_qh;
                        }
                        else
                        {
                            if (strparm.factory_code.Contains("sc"))
                            {
                                in_con = con_yb;
                            }
                            else
                            {
                                if (strparm.factory_code.Contains("gz"))
                                {

                                }
                                else
                                {
                                    strMsg = "factory_code=<" + strparm.factory_code + "> not find ";
                                }                                
                            }
                        }
                    }
                }

                if (strMsg == "")
                {

                    if (strparm.factory_code.Contains("gz"))
                    {
                        dic = new Dictionary<string, string>(); //查询公用dic
                        dic.Add("ccode", fy_code);//查询对应物流计划
                        DataTable fy_dt = MethodHelp.GetTableInfo("TMS0062", dic, con);//获取物流计划明细，订单数据源
                        if (fy_dt.Rows.Count>0)
                        {
                            WMS_CarInfoInPutRequestDto data = new WMS_CarInfoInPutRequestDto();
                            WMS_CarInfoInPutHeaderDto header = new WMS_CarInfoInPutHeaderDto();
                            List<WMS_CarInfoInPutHeader> header_input = new List<WMS_CarInfoInPutHeader>();
                            dic = new Dictionary<string, string>(); //查询公用dic
                            dic.Add("ccode", fy_code);//查询对应物流计划                           
                            DataTable sod_dt = MethodHelp.GetTableInfo("TMS0063", dic, con);//获取物流计划明细，订单数据源
                            if (sod_dt.Rows.Count > 0)
                            {
                                List<WMS_CarInfoInPutDetails> details_input = new List<WMS_CarInfoInPutDetails>();
                                //循环插入明细
                                foreach (DataRow row in sod_dt.Rows)
                                {
                                    details_input.Add(new WMS_CarInfoInPutDetails
                                    {
                                        logPlanNo = row["planid"].ToString(),
                                        salesOrderNo = row["salesorderno"].ToString(),
                                        cusAddress =row["endaddress"].ToString(),
                                        cusContact = row["lx_user"].ToString()+','+ row["lx_tele"].ToString(),
                                        endCustomer = ""
                                    });
                                }

                                //添加到header
                                if (details_input != null)
                                {
                                    header_input.Add(new WMS_CarInfoInPutHeader
                                    {
                                        waybillNo = fy_dt.Rows[0]["ccode"].ToString(),
                                        driverName = fy_dt.Rows[0]["drivername"].ToString(),
                                        carNo = fy_dt.Rows[0]["carno2"].ToString(),
                                        driverTel = fy_dt.Rows[0]["telephone"].ToString(),
                                        driverIdcard = fy_dt.Rows[0]["identityno"].ToString(),
                                        carrierName = fy_dt.Rows[0]["carriername"].ToString(),                                  
                                        details = details_input
                                    });
                                }


                            }
                            else
                            {
                                strMsg = "运单号=<" + fy_code + "> 找不到对应明细信息!";
                            }

                            if (header_input!=null)
                            {
                                header.header = header_input;
                            }
                            if (header!=null)
                            {
                                data.data = header;
                            }


                            if (data!=null)
                            {
                                Dictionary<string, string> urldic = new Dictionary<string, string>(); //URL获取dic
                                urldic.Add("function_description", "内部:组件WMS_车辆信息新增");//查看URL配置表地址描述
                                DataTable url_dt = MethodHelp.GetTableInfo("TMS0004", urldic, con);//获取URL地址
                                if (url_dt.Rows.Count > 0)
                                {
                                    string jsonText = JsonConvert.SerializeObject(data);
                                    var reAgv = DB.httpPost(url_dt.Rows[0]["interface_url"].ToString(), jsonText, "", "否");
                                    WMS_CarInfoInPutResponseDto psp = JsonConvert.DeserializeObject<WMS_CarInfoInPutResponseDto>(reAgv);
                                    if (psp.code > 0)
                                    {
                                        strMsg ="WMS ERR:" + psp.message;
                                    }
                                }                                
                            }



                        }
                        else
                        {
                            strMsg = "运单号=<" + fy_code + "> 找不到对应主表信息!";
                        }
                    }                   
                                    
                }
            }
            catch (Exception ex)
            {
                strMsg = ex.ToString();
            }

            if (strMsg == "")
            {
                re.code = 0;
                re.message = "";
            }
            else
            {
                re.code = 500;
                re.message = strMsg;

            }


            _logger.LogInformation(JsonConvert.SerializeObject(re));
            return new JsonResult(re);

        }


    }
}
